package yxy.game.pm2.command.pickedtroops;

import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.commandertally;
import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Currency;
import yxy.game.pm2.bean.PickedTroopsSlot;
import yxy.game.pm2.bean.mq.CCReason;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.PickedTroopsMessage;
import yxy.game.pm2.module.CurrencyHandle;

/****************************************
 * @name CMD_PickedTroopsSlotResolve
 * @description 兵符分解
 * @author 梁健彬
 * @since 2022-05-20
 ***************************************/
@MessageType(proto = Command.PickedTroopsSlotResolve, classtype = PickedTroopsMessage.PickedTroopsSlotResolveRequest.class)
public class CMD_PickedTroopsSlotResolve extends Command<PickedTroopsMessage.PickedTroopsSlotResolveRequest> {

    @Override
    public void execute(MessageSource messageSource, PickedTroopsMessage.PickedTroopsSlotResolveRequest request) {
        String playerCode = messageSource.getTag();//playercode
        String slotCode = request.getSlotCode();//兵符code

        PickedTroopsMessage.PickedTroopsSlotResolveResponse.Builder response = PickedTroopsMessage.PickedTroopsSlotResolveResponse.newBuilder();

        try {
            //判断兵符是否存在
            PickedTroopsSlot slot = PickedTroopsSlot.get(playerCode, slotCode);
            if (slot == null) {
                send(messageSource, response, Result.ParamError);
                return;
            }

            //正在使用则不能分解(保险)
            if (slot.getUse()) {
                send(messageSource, response, Result.ParamError);
                return;
            }

            //分解返回
            commandertally data = DataCenter.getData(slot.getDataId(), commandertally.class);
            Currency back = Currency.create(data.getDecomposetpe(), data.getDecomposetpeid(), data.getDecomposetpenum());
            new CurrencyHandle().addCurrency(playerCode, CCReason.兵符, back);

            //移除
            PickedTroopsSlot.remove(playerCode, slot);

            response.addItem(new CurrencyHandle().packItem(back));
            response.setSlotCode(slotCode);
            send(messageSource, response, Result.Success);
        } catch (Exception e) {
            e.printStackTrace();
            send(messageSource, response, Result.DataError);
        }
    }

    private void send(MessageSource messageSource, PickedTroopsMessage.PickedTroopsSlotResolveResponse.Builder response, Result result) {
        response.setResult(result.packResult());
        MessageEmitterHandler.getInstance().send(messageSource, response.build());
    }
}